import reqUrl from './reqUrl'
import User from "./user";
export default {
	config:{
		baseUrl:reqUrl,
		header:{
			'Content-Type':'application/json;charset=UTF-8',
			'Content-Type':'application/x-www-form-urlencoded'
		},
		data: {},
		method: "GET",
		dataType: "json",
	},
	request(options = {}){
		options.header = options.header || this.config.header;
		options.method = options.method || this.config.method;
		options.dataType = options.dataType || this.config.dataType;
		options.url = this.config.baseUrl+options.url;
		if (options.token) {
			// 验证用户是否登录 
			if (!this.checkToken(options.checkToken)) return;
			options.header.token = User.token;
		}
		return uni.request(options);
	},
	get(url,data,options={}){
		options.url = url;
		options.data = data;
		options.method = 'GET';
		return this.request(options);
	},
	post(url,data,options={}){
		options.url = url;
		options.data = data;
		options.method = 'POST';
		return this.request(options);
	},
	put(url,data,options={}){
		options.url = url;
		options.data = data;
		options.method = 'PUT';
		return this.request(options);
	},
	delete(url,data,options={}){
		options.url = url;
		options.data = data;
		options.method = 'DELETE';
		return this.request(options);
	},
	errorCheck(err,res,errfun = false,resfun = false){
		if (err) {
			typeof errfun === 'function' && errfun();
			uni.showToast({ title: '加载失败',icon:"none" });
			return false;
		}
		if (res.data.errorCode) {
			typeof errfun === 'function' && resfun();
			uni.showToast({ title: res.data.msg,icon:"none" });
			return false;
		}
		return true;
	},
	checkToken(checkToken){
		if (checkToken && !User.token) {    
			uni.showToast({ title: '授权登录过期,请重新登录', icon:"none" })
			uni.navigateTo({
				url: '/pages/login/login'
			});
			return false;
		}
		return true;
	}
}